<?php

namespace App\V3\V3_1\Controllers;

use App\V3\V3_1\Models\MaterielOtherChargesModel;
use App\V3\V3_1\Services\MaterielService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class MaterielController extends BaseController
{
    public function materielInStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'status' => [
                'required',
                Rule::In([1, 2]),
            ],//入库状态：1-全部 2-部分
            'in_storage_time' => 'date_format:Y-m-d H:i:s',//入库时间
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(empty($data['content'])) {
            return $this->fail('', '请填写采购内容');
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['is_use_shelf'] = $this->isUseShelf();

        $this->log('采购单入库', $data);

        return response()->json(
            MaterielService::materielInStorage(
                $data
            )
        );
    }

    /**
     * 采购列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/18 16:05
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|numeric|min:1',//页面大小
            'currentPage' => 'required|numeric|min:1',//当前页码
            'search_type'=>[
                'required',
                Rule::In([0,1,2,3,4,5,6,7,8])
            ],
            'status'=>[
                'required',
                Rule::In([0,1,2,3,4,5,6])
            ]
        ],[
            'pageSize.required' => '参数`页面大小`缺失',
            'pageSize.numeric' => '参数`页面大小`仅能为数字',
            'pageSize.min' => '参数`页面大小`最小只能为1',
            'currentPage.required' => '参数`页码`缺失',
            'currentPage.numeric' => '参数`页码`仅能为数字',
            'currentPage.min' => '参数`页码`最小只能为1',
            'search_type.required' => '参数`搜索类型`缺失',
            'search_type.in' => '参数`搜索类型`不合法',
            'status.required' => '参数`状态`缺失',
            'status.in' => '参数`状态`不合法',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(isset($request->start_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'start_time' => 'date_format:Y-m-d H:i:s',//页面
            ],[
                'start_time.date_format' => '开始时间格式错误，例：'.date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        if(isset($request->end_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'end_time' => 'date_format:Y-m-d H:i:s',//页面
            ],[
                'end_time.date_format' => '结束时间格式错误，例：'.date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        if($this->getUserId() == $this->getMainUserId()){
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            if($this->isSharePurchase()) {
                $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            }
            else {
                $userId['a.user_id'] = ['EQ' => $this->getUserId()];
            }
        }

        return $this->success(
            MaterielService::list($data, $userId)
        );
    }

    public function payHistory(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ],[
            'id.required' => '参数`采购单id`是必须的'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            MaterielService::payHistory($request->id)
        );
    }

    public function cancel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(
            MaterielService::cancel(
                $this->getMainUserId(),
                $data
            )
        );
    }

    /**
     * @重新下单
     * created 在 2021/11/26 10:53 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAgain(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['purchase_no'] = self::createPurchaseNo();

        return $this->success(
            MaterielService::addAgain(
                $this->getUserId(),
                $this->getMainUserId(),
                $data
            )
        );
    }

    //创建采购单号
    private function createPurchaseNo()
    {
        list($t1, $t2) = explode(' ', microtime());
        $str =(float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
        $millisecond = substr($str,10,13);
        $date = date("YmdHis").$millisecond.mt_rand(100000,999999);

        return $date;
    }

    /**
     * @修改采购单
     * created 在 2021/11/24 14:52 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('删除采购', $data);
        return response()->json(
            MaterielService::del($data)
        );
    }

    /**
     * @详细
     * created 在 2021/11/26 14:53 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        return $this->success(
            MaterielService::detail(
                $data
            )
        );
    }

    /**
     * @其他费用列表
     * created 在 2021/11/25 15:00 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function chargesList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'materiel_id' =>'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = MaterielOtherChargesModel::where('materiel_id',$data['materiel_id'])->get();
        return $this->success($model);
    }

    /**
     * @修改采购单
     * created 在 2021/11/25 14:09 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCharges(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'materiel_id' =>'required|integer',//销售单主键id
            'money' =>'required|string',//其他费用
            'other_type_name' =>'required|string',//其他费用类型名称
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();

        $this->log('添加采购其他费用', $data);
        return response()->json(
            MaterielService::addCharges($data)
        );
    }

    /**
     * @编辑其他费用
     * created 在 2021/11/25 14:48 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editCharges(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//其他费用主键id
            'money' =>'required|string',//其他费用
            'other_type_name' =>'string',//其他费用类型名称
            'other_remark' =>'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('添加采购其他费用', $data);
        return response()->json(
            MaterielService::editCharges($data)
        );
    }

    /**
     * @付款
     * created 在 2021/11/25 15:36 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function payMaterielMoney(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'materiel_id'=>'required|integer',//销售单主键
            'money'=>'required|string',//收款金额
            'pay_time'=>'required|date',//收款时间
            'payer_account'=>'required|string',//收款账号
            'status' => [
                'required',
                Rule::In([1, 2]),
            ],//收款状态：1-全部 2-部分
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['pay_time'] = strtotime($data['pay_time']);
        $data['created_at'] = time();

        $this->log('采购付款', $data);

        return response()->json(
            MaterielService::payMaterielMoney($data)
        );
    }

    /**
     * @新建采购单
     * created 在 2021/11/23 15:52 创建
     * updated at 2022/05/25 16:04
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        if(empty($request->materiel_content)) {
            return $this->fail('', '请添加需采购的物料产品');
        }

        $info = self::checkInput($data = $request->all());

        if($info) {
            return $info;
        }

        if(!in_array(empty($request->source)?1:$request->source, [1,2,3,4,5])) {
            return $this->fail('', '订单来源不合法，请重试');
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['purchase_no'] = self::createPurchaseNo();
        $data['remark'] = empty($data['remark'])?'':$data['remark'];

        $this->log('新建采购单', $data);

        return response()->json(MaterielService::add($data));
    }

    private function checkInput($data)
    {
        //参数验证
        $validator = Validator::make($data, [
            'supplier_customer_id' =>'required|integer',//供应商id
            'purchase_time' => 'required',//采购日期
            /* 'tax_rate' =>'required|integer|min:0',//税率 */
            // 'other_charges' => 'integer|min:0',//其他费用
            'preferential_way' => [
                'required',
                Rule::In([0, 1, 2]),
            ],//优惠方式;0:无;1:修改价格;2:折扣优惠;
            'preferential_money' =>'numeric|min:0',//优惠方式对应金额
        ]);

        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
    }

    /**
     * @修改采购单
     * created 在 2021/11/24 14:52 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        if(empty($request->materiel_content)) {
            return $this->fail('', '请添加需采购的物料产品');
        }

        if(empty($request->id) || !is_numeric($request->id)) {
            return $this->fail('', '参数`id`缺失');
        }

        $info = self::checkInput($data = $request->all());

        if($info) {
            return $info;
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        $this->log('修改采购单', $data);
        return response()->json(MaterielService::edit($data));
    }

}
